﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.MiniApi.Middlewares
 * 唯一标识：44d94cbe-2292-4a86-8f4a-c902bb1bb0e3
 * 文件名：ExceptionHandlerMiddleware
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2023/12/21 10:38:04
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

namespace Vampirewal.Core.MiniApi;

/// <summary>
/// 全局异常捕获
/// </summary>
internal class ExceptionHandlerMiddleware
{
    private readonly RequestDelegate _next;

    /// <summary>
    /// 构造函数
    /// </summary>
    public ExceptionHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    //同步下名称必须为Invoke、异步下名称必须是InvokeAsync
    public async Task InvokeAsync(HttpContext context)
    {
        var resultProvider = VampirewalCoreContext.GetInstance().GetService<IVampirewalMiniApiResultProvider>();

        if (resultProvider == null)
        {
            await _next(context);
        }
        else
        {
            try
            {
                //捕捉没个管道中间件中的错误
                await _next(context);
            }
            catch (Exception exception)
            {
                await Handler(context, exception, resultProvider);
            }
        }
    }

    private async Task Handler(HttpContext context, Exception exception, IVampirewalMiniApiResultProvider Provider)
    {
        // 返回json类型
        context.Response.ContentType = "application/json";
        var response = context.Response;

        switch (exception)
        {
            case ApplicationException ex:
                {
                    break;
                }
            case KeyNotFoundException ex:
                {
                    break;
                }
            default:
                {
                    //继承之前的错误类型码
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    //errorResponse.Message = exception.Message;
                    break;
                }
        }

        var data = await Provider.OnErrorResultProvider(exception.Message, (int)HttpStatusCode.InternalServerError);

        var res = System.Text.Json.JsonSerializer.Serialize(data);
        await context.Response.WriteAsync(res);
    }

}